package com.wwwarehouse.taskcenter.fragment.job_point.step5;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.flexbox.AlignContent;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayout;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.UXRadioButton;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.CharacterByteUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.AddJobPointStep5LookItemMesResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @创建者 minifly.
 * @创建时间 2017/10/25 21:19
 * @描述 添加多个单元组
 */

@SuppressWarnings("ResourceType")
public class ChooseJobUnitShowallMessageFragment extends BaseFragment implements View.OnClickListener {

    private View mView;
    private ClearEditText mTaskAddpointStep5ShowallEdittext;
    private TextInputLayout mTaskAddpointStep5ShowallInputlayout;
    private UXRadioButton mTaskAddpointStep5ShowallSameradio;
    private UXRadioButton mTaskAddpointStep5ShowallNosameradio;
    private FlexboxLayout mTaskAddpointStep5ShowallFlexlayout;
    private Button mTaskAddpointStep5ShowallConfirmBtn;
    private AddJobPointStep5LookItemMesResponseBean selectBean;
    private String jobPointUkid;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_choose_showall_message, container, false);
        initView(mView);
        return mView;
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseJobUnitShowallMessageFragment) {
            mActivity.setTitle("" + getString(R.string.new_task_step5_judege_unit));
        }
    }

    @Override
    public void requestDatas() {

    }

    private void initView(View mView) {
        mTaskAddpointStep5ShowallEdittext = (ClearEditText) mView.findViewById(R.id.task_addpoint_step5_showall_edittext);
        mTaskAddpointStep5ShowallInputlayout = (TextInputLayout) mView.findViewById(R.id.task_addpoint_step5_showall_inputlayout);
        mTaskAddpointStep5ShowallSameradio = (UXRadioButton) mView.findViewById(R.id.task_addpoint_step5_showall_sameradio);
        mTaskAddpointStep5ShowallNosameradio = (UXRadioButton) mView.findViewById(R.id.task_addpoint_step5_showall_nosameradio);
        mTaskAddpointStep5ShowallFlexlayout = (FlexboxLayout) mView.findViewById(R.id.task_addpoint_step5_showall_flexlayout);
        mTaskAddpointStep5ShowallConfirmBtn = (Button) mView.findViewById(R.id.task_addpoint_step5_showall_sameradioconfirm_btn);
        mTaskAddpointStep5ShowallConfirmBtn.setOnClickListener(this);
        Bundle bundle = getArguments();
        selectBean = bundle.getParcelable("data");

        jobPointUkid = bundle.getString("jobPointUkid");

        TextView textView ;
        //布局方向
        mTaskAddpointStep5ShowallFlexlayout.setFlexDirection(FlexDirection.ROW);
        //正常换行
        mTaskAddpointStep5ShowallFlexlayout.setFlexWrap(FlexWrap.WRAP);
        //副轴起点对齐
        mTaskAddpointStep5ShowallFlexlayout.setAlignContent(AlignContent.FLEX_START);

        mTaskAddpointStep5ShowallFlexlayout.removeAllViews();
        if(selectBean!=null){
            ArrayList<AddJobPointStep5LookItemMesResponseBean.ListBean> lists = selectBean.getList();
            for(AddJobPointStep5LookItemMesResponseBean.ListBean bean : lists){
                textView = new TextView(mActivity);
                if(TextUtils.isEmpty(bean.getUnitName())){
                    textView.setText(" " + bean.getCategoryName() + "("+  bean.getCount() + ") ");
                }else{
                    textView.setText(" " + bean.getCategoryName() + "("+  bean.getCount() + bean.getUnitName()+ ") ");
                }
                textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
                textView.setHeight(ConvertUtils.dip2px(mActivity,20));
                textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                textView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));

                if(bean.getCount() == 0 ){
                }else{
                    mTaskAddpointStep5ShowallFlexlayout.addView(textView);
                }

            }
        }

        //限制字数
        CharacterByteUtils.limitLength(mTaskAddpointStep5ShowallEdittext,30);

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.task_addpoint_step5_showall_sameradioconfirm_btn) {
            //选择共用与不共用去的地方不一样。  共用到的是选择套餐的页面， 不共用用的是完成此步的页面
            if("".equals(mTaskAddpointStep5ShowallEdittext.getText().toString().trim())){
                toast("请填写作业单元名称");
            }else{
                saveData();
            }
        }
    }

    /**
     * 共享单位的添加
     */
    public void saveData(){
        Map<String,Object > map  = new HashMap<>();
        /**
         businessUnitId	业务单位id	number	@mock=10000001
         isCommon	是否设置共享 1：共享 0 不共享	string	@mock=1
         jbUnitFactors|3		array<object>
         memberName	成员名字（人：人）,具体类目，现实物的名称	string	@mock=$order('人','物','类目')
         memberNum	成员数量	number	@mock=$order('1','2','2')
         memberType	成员类型（PERSON:人，ITEM:物，CATEGORY:类目）	string	@mock=$order('PERSON','ITEM','CATEGORY')
         memberUkid	成员ukd(人：999)	number	@mock=$order(''122,1555'','5555')
         menberNumUnit	成员单位（人：个）	string	@mock=$order('个','件','件')
         menberNumUnitUkid	成员单位 ukid	number
         jbUnitName	作业单元名称	string	@mock=作业单元1
         jobPointUkid	作业点ukid	number	@mock=100000110
         */
        try {
            map.put("businessUnitId",Long.parseLong(BaseApplication.sp.getValue(TaskCenterConstant.CONSTANT_BUSINESSID)));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //1：共享
        if(mTaskAddpointStep5ShowallSameradio.isChecked()){
            map.put("isCommon","1");
        }else{ //0 不共享
            map.put("isCommon","0");
        }
        map.put("jbUnitName","" + mTaskAddpointStep5ShowallEdittext.getText().toString());

        try {
            map.put("jobPointUkid",Long.parseLong(jobPointUkid));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        Map<String,Object> jbUnitFactors;
        List list = new LinkedList();
        if(selectBean!=null){
            ArrayList<AddJobPointStep5LookItemMesResponseBean.ListBean> lists = selectBean.getList();
            for(AddJobPointStep5LookItemMesResponseBean.ListBean bean : lists){
                if(bean.getCount() == 0 ){

                }else{
                    jbUnitFactors = new HashMap<>();
                    jbUnitFactors.put("memberName",""+bean.getCategoryName());
                    jbUnitFactors.put("memberNum", bean.getCount());
                    jbUnitFactors.put("memberType","ITEM");
                    jbUnitFactors.put("memberUkid",bean.getMetaCategoryUkid());
                    jbUnitFactors.put("menberNumUnit",bean.getUnitName());
                    if(TextUtils.isEmpty(bean.getUnitUkid())){
                        jbUnitFactors.put("menberNumUnitUkid",null);
                    }else{
                        jbUnitFactors.put("menberNumUnitUkid",bean.getUnitUkid());
                    }
                    list.add(jbUnitFactors);
                }

            }
        }

        map.put("jbUnitFactors",list);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_ADD_JOBPOINT_STEP5_SHAREPOINTBINDING,map,myResponse,10001);
        showProgressDialog();
    }

    NoHttpUtils.OnResponseListener myResponse = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int i) {
            if("0".equals(commonClass.getCode())){
                BaseApplication.sp.putBooleanValue("isCanfinish",true);
                ////选择共用与不共用去的地方不一样。  共用到的是选择套餐的页面， 不共用用的是完成此步的页面
                //1：共享
                if(mTaskAddpointStep5ShowallSameradio.isChecked()){
                    Bundle bundle = new Bundle();
                    bundle.putString("jobPointUkid","" + jobPointUkid);
                    ChooseJobUnitHavedUnitPagerFragment5 fragment5 = new ChooseJobUnitHavedUnitPagerFragment5();
                    fragment5.setArguments(bundle);
                    pushFragment(fragment5);
                }else{ //0 不共享 直接到新增的页面
                    BaseApplication.sp.putBooleanValue("isCanfinish",true);
                    Bundle bundle = new Bundle();
                    bundle.putString("jobPointUkid" , jobPointUkid);
                    ChooseJobUnitAddFirstpageFragment5 protectTaskUnitFragment = new ChooseJobUnitAddFirstpageFragment5();
                    protectTaskUnitFragment.setArguments(bundle);
                    pushFragment(protectTaskUnitFragment);
                }

            }else{
                toast("" + commonClass.getMsg());
            }
        }

        @Override
        public void onFailed(String s, int i) {
        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };
}
